<!DOCTYPE html>
<html lang="">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>document.cookie demo</title>
</head>

<body>
    <p>document.cookie demo</p>
    <script>
        var setCookie = function (cookie_name, value, day) {

            if (day != null) {
                //expires为失效日期，以毫秒计算
                console.log("此cookie走的是if流程", cookie_name)
                var expires = day * 24 * 60 * 60 * 1000;
                var date = new Date(+new Date() + expires);
                //+new Date()是取得当前时间毫秒值的简略写法，等价于new Date().getTime();
                document.cookie = cookie_name + "=" + escape(value) +
                    ((day == null) ? "" : ";expires=" + date.toGMTString());

            } else {
                console.log("此cookie走的是else流程", cookie_name)
                var date = new Date(+new Date());
                document.cookie = cookie_name + "=" + escape(value) + ";expires=" + date.toGMTString();
            }
        };

        var delCookie = function (cookie_name) {
            setCookie(cookie_name, '', -1);
        }
        
        //getCOokie
        var getCookie = function (cookie_name) {
            var arr;
            var reg = new RegExp();
            if (arr = document.cookie.mathc(reg)
                return unescape(arr[2]);
            else
                return null;
        }

        //写入有效期为365天的cookie
        //成功
        setCookie("firstName", "James", 365);

        //写入有效期为0天的cookie
        //立即失效 ======在控制台看不到，当然后续也使用不到
        setCookie("lastName", "LeBron", 0);

        //写入有效期为负数的cookie
        //立即失效======在控制台看不到，当然后续也使用不到
        setCookie("Career", "Player", -1);

        //没有日期参数，会走else流程
        setCookie("parameter", "noParameter");

        //向cookie直接写入：有效期为当前时刻的testCurrent字段
        //不能在chrome看到cookie，因为立即失效。
        document.cookie = 'testCurrent=Invalid;expires=' + new Date().toUTCString();

        //向cookie直接写入：有效期为10秒，的testCurrent字段
        //在chrome调试工具中，看到10秒后cookie消失，
        document.cookie = 'testCurrent=Invalid;expires=' + new Date(+new Date() + 10000).toUTCString();
    </script>
</body>

</html>